package com.xiaomaoguai.fcp.pre.kepler.trace.interceptor;

import com.xiaomaoguai.fcp.pre.kepler.trace.constants.KeplerTraceConstant;
import com.xiaomaoguai.fcp.pre.kepler.trace.exception.JaegerException;
import com.xiaomaoguai.fcp.pre.kepler.trace.service.DataDesensitization;
import io.opentracing.Span;
import lombok.experimental.Delegate;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @author August.Zhang
 * @version v1.0.0
 * @date 2020/1/8 20:22
 * @since JDK 1.8
 */
public abstract class AbstractHandlerInterceptor implements HandlerAroundInterceptor, DataDesensitization {

	@Delegate
	@Resource
	protected DataDesensitization jaegerDataDesensitization;

	@Resource
	private HandlerInterceptorFactory handlerInterceptorFactory;

	@Value("${" + KeplerTraceConstant.KEPLER_JAEGER_TRACE_SEPARATE_SPAN_ENABLED + ":true}")
	protected Boolean traceOpentracingSeparateSpanEnabled;

	@PostConstruct
	public void init() {
		handlerInterceptorFactory.registerSingleFactory(getClass().getSimpleName(), this);
	}

	@Override
	public String getOperationName(final ProceedingJoinPoint pjp) {
		return pjp.getSignature().getDeclaringType().getSimpleName();
	}

	@Override
	public void beforeMethod(final ProceedingJoinPoint pjp, final Span span) throws JaegerException {
		try {
			invokeBeforeMethod(pjp, span);
		} catch (Exception e) {
			throw new JaegerException(e);
		}
	}

	@Override
	public void afterMethod(final ProceedingJoinPoint pjp, final Span span) throws JaegerException {
		try {
			invokeAfterMethod(pjp, span);
		} catch (Exception e) {
			throw new JaegerException(e);
		}
	}

	protected abstract void invokeBeforeMethod(final ProceedingJoinPoint pjp, final Span span);

	protected abstract void invokeAfterMethod(final ProceedingJoinPoint pjp, final Span span);

}
